//
//  PictureBrowserCell.swift
//  01MicroBlog
//
//  Created by Apple on 15/8/9.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit
import SDWebImage

protocol PictureBrowserCellDelegate: NSObjectProtocol {
    func pictureZooming(rate:CGFloat)
    func pictureEndZooming()
}

class PictureBrowserCell: UICollectionViewCell {
    
    weak var pictureDelegate:PictureBrowserCellDelegate?
    
    var index:Int = 0
    
    var imageUrl:NSURL? {
        didSet {
            
            indicatorView.startAnimating()
            
            imageView.image = nil
            // 模拟用户延迟
            let when = NSEC_PER_SEC * 0
            dispatch_after(when, dispatch_get_main_queue()) {
                self.imageView.sd_setImageWithURL(self.imageUrl, placeholderImage: nil) { (image, _ , _ , _ ) -> Void in
                    if image != nil {
                        
                        self.indicatorView.stopAnimating()
                        
                        self.imageView.image = image
                        
                        self.setupImageViewFrame()
                    }
                }
            }
           
        }
    }

    private func setupImageViewFrame() {
        
        let imgSize = displayImageSize()
        let h = scrollView.bounds.height
        if imgSize.height < h {
            let y = (h - imgSize.height) * 0.5
            imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: imgSize)
            
            // 用边距把imageView挤到中间
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        } else {
            imageView.frame = CGRect(origin: CGPointZero, size: imgSize)
            scrollView.contentSize = imgSize
        }
    }
    
    private func displayImageSize() -> CGSize {
        let image = imageView.image
        let rate = (image?.size.height)! / (image?.size.width)!
        let width  = scrollView.bounds.size.width
        let height = width * rate
        
        return CGSize(width: width, height: height)
    }
    
   override init(frame: CGRect) {
        super.init(frame: frame)
    
        setupUI()
    }
    
    private func setupUI() {
        
        // 1.添加控件
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        contentView.addSubview(indicatorView)
        
        // 2.自动布局
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv":scrollView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv":scrollView]))
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
       
        // 测试下rollerView
//        scrollView.backgroundColor = UIColor.redColor()
        
        scrollView.delegate = self
        scrollView.maximumZoomScale = 2.0
        scrollView.minimumZoomScale = 0.5
        
    }
    
    func resetScrollView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentSize = CGSizeZero
        scrollView.contentOffset = CGPointZero
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    
    // MARK: - 懒加载控件
    private lazy var scrollView = UIScrollView()
    lazy var imageView = UIImageView()
    private lazy var indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
}

// MARK: - PictureBrowserCell代理方法
extension PictureBrowserCell:UIScrollViewDelegate {
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
//        print(view?.transform)
        // 重新计算间距
        // 通过 transform 改变view的缩放，bound本身没有变化，frame会变化
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        // 如果边距小于0，需要修正
        offsetX = offsetX < 0 ? 0 : offsetX
        
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        offsetY = offsetY < 0 ? 0 : offsetY
        
        // 用边距将图片框挤到中间
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        
        pictureDelegate?.pictureEndZooming()
    }
    
    // 获取缩放值
    func scrollViewDidZoom(scrollView: UIScrollView) {
        
        pictureDelegate?.pictureZooming(imageView.transform.a)
        
    }
    
}
